package cn.kgc.tangcco.tcbd1011.comm.base;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.kgc.tangcco.tcbd1011.util.Util;


/**
 * Servlet implementation class BaseServlet
 */
@WebServlet(urlPatterns="/base.action",name="BaseServlet")
public class BaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BaseServlet() {
        super();
    }
    public String prefix() {
    	return "/WEB-INF/jsp/";
    }
    public String suffix() {
    	return ".jsp";
    }
    
    private void forward(HttpServletRequest request,HttpServletResponse response,String forward) throws ServletException, IOException {
    	request.getRequestDispatcher(prefix()+forward+suffix()).forward(request, response);
    }
    
    
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String methodName=request.getParameter(Util.METHODNAME);
		if (methodName!=null&&!methodName.isEmpty()) {
			try {
				Method method=this.getClass().getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
				String forward=(String) method.invoke(this, request,response);
				if (methodName.startsWith(Util.DOADD)||methodName.startsWith(Util.DOUPDATE)||methodName.startsWith(Util.DODELETE)) {
					response.sendRedirect(forward);
				}else {
					this.forward(request, response, forward);
				}
			} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
				e.printStackTrace();
			}
		}
	}
    
    
}
